﻿

'*******************************************************************
' Program: Data Center Visio Rack Tool
' Author: Albert E Edlund
' Date:
'
' Purpose:
'
'
'*******************************************************************

Imports Microsoft.Practices.EnterpriseLibrary.Common
Imports Microsoft.Practices.EnterpriseLibrary.Data
Imports Microsoft.Practices.EnterpriseLibrary.ExceptionHandling
Imports Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging

Imports System
Imports System.Windows.Forms
Imports System.Text
Imports System.Data
Imports System.Threading
Imports System.Timers
Imports System.Drawing
Imports System.Drawing.Image
Imports System.Drawing.Imaging
Imports System.Drawing.Printing
Imports System.Runtime.InteropServices

Imports System.IO
Imports System.Xml
Imports System.Xml.Serialization

Imports Microsoft.Reporting
Imports Microsoft.Reporting.WinForms
Imports Microsoft.ReportingServices
Imports Microsoft.ReportingServices.ReportRendering

Imports System.ComponentModel

Imports visRackAppConnectivity
Imports visRackAppConnectivity.clsDC_RackData



Public Class clsDC_RackReporting
    Implements IDisposable


#Region " Properties and declarations "


    Public m_db As Database
    Public m_ds As DataSet

    Private m_filename As String = ""

    Private m_currentPageIndex As Integer = 0
    Private m_streams As IList(Of Stream)
    Private m_colcolnames As Collection


    ' name that maps between our local report and the datasource defined in the report definition
    Private m_datasource As String
    Public Property _DataSource() As String
        Get
            Return m_datasource
        End Get
        Set(ByVal value As String)
            If (value Is Nothing) Then
                Throw New System.ArgumentNullException("_DataSourceValueIsNull", _
                    "Report _DataSource is Null.")
            End If
            m_datasource = value
        End Set
    End Property

    ' pointer to report defintion 
    Private m_embedded As String
    Public Property _Embedded() As String
        Get
            Return m_embedded
        End Get
        Set(ByVal value As String)
            m_embedded = value
        End Set
    End Property

    ' datatable used for report defintion
    Private m_dt As System.Data.DataTable
    Public Property _DataTable() As System.Data.DataTable
        Get
            Return m_dt
        End Get
        Set(ByVal value As System.Data.DataTable)
            If (value Is Nothing) Then
                Throw New System.ArgumentNullException("_DataTableValueIsNull", _
                    "Report _DataTable is Null.")
            End If
            m_dt = value
        End Set
    End Property

    ' 
    Private m_reportname As String
    Public Property _ReportName() As String
        Get
            Return m_reportname
        End Get
        Set(ByVal value As String)
            m_reportname = value
        End Set
    End Property

    Private m_displayname As String
    Public Property _DisplayName() As String
        Get
            If m_displayname = "" Then
                Return _ReportName
            Else
                Return m_displayname
            End If
        End Get
        Set(ByVal value As String)
            m_displayname = value
        End Set
    End Property

    ' the report viewer associated with this reporting class
    Private m_localviewer As ReportViewer
    Public Property _LocalViewer As ReportViewer
        Get
            Return m_localviewer
        End Get
        Set(ByVal value As ReportViewer)
            m_localviewer = value
        End Set
    End Property

    ' the predefined report that we are attempting to create
    Private m_intReport As baseReports
    Public Property _baseReport As baseReports
        Get
            Return m_intReport
        End Get
        Set(ByVal value As baseReports)
            If Not TypeDescriptor.GetConverter(GetType(baseReports)).IsValid(value) Then
                Throw New ArgumentException()
            End If
            m_intReport = value
        End Set
    End Property


    Private m_filepath As String = ""
    Public Property _FilePath() As String
        Get
            Return m_filepath
        End Get
        Set(ByVal value As String)
            m_filepath = value
        End Set
    End Property

    Private m_targetformat As String = ""
    Public Property _TargetFormat() As String
        Get
            Return m_targetformat
        End Get
        Set(ByVal value As String)
            m_targetformat = value
        End Set
    End Property

    Private m_targetwindow As IntPtr = -1
    Public Property _TargetWindow() As IntPtr
        Get
            Return m_targetwindow
        End Get
        Set(ByVal value As IntPtr)
            m_targetwindow = value
        End Set
    End Property

    ' the table definitions for the solution
    Private m_ObjectTable As DC_RackTables
    Public Property _ObjectTable As DC_RackTables
        Get
            Return m_ObjectTable
        End Get
        Set(ByVal value As DC_RackTables)
            If Not TypeDescriptor.GetConverter(GetType(DC_RackTables)).IsValid(value) Then
                ' Throw New ArgumentException()
                m_ObjectTable = DC_RackTables.tblUnknown
            Else
                m_ObjectTable = value
            End If
        End Set
    End Property

    ' just in case we want to call sql directly
    Private m_sqlCall As String
    Public Property _SQLcall As String
        Get
            Return m_sqlCall
        End Get
        Set(ByVal value As String)
            m_sqlCall = value
        End Set
    End Property



#End Region

#Region " Enumerations "

    '
    ' master set of reports - everything should be defined here
    ' so that we can validate calls
    '
    Public Enum baseReports

        rptUnknown

        '
        ' icmp reports
        '
        rptIcmpStepPing
        rptIcmpChartStepPing
        rptIcmpTraceRoute
        '
        ' snmp reports
        '
        rptSnmpSystem
        rptSnmpInterfaces
        rptSnmpAddrTable
        rptSnmpRoute
        rptSnmpIcmp
        '
        'wmi reports
        '
        rptWmiProcessor
        rptWmiOperatingSystem
        rptWmiLogicalDisks
        rptWmiComputerSystem
        rptWmiDiskPartition
        rptWmiNetworkAdapter
        rptWmiNetworkAdapterConfiguration
        rptWmiNtLogEvent
        '
        ' location related reports
        '

        rptLocationsAll
        rptAttrLocationsAll
        rptAttrGeoDataAll
        rptCabinetRowsAll
        '
        ' software reports
        '
        rptApplicationsAll
        rptApplicationsMoveStatus
        rptApplicationsNetwork
        rptApplicationsOperations
        rptOSAll
        rptVHAll
        rptAppConnectionsAll
        rptAppSolutionsAll
        '
        ' physicalcomponents/storage/disk reports
        '
        rptAttrProcessorsAll
        rptAttrDrawAll
        rptDiskLogicalsAll
        rptDiskPhysicalsAll
        rptDiskESAll
        rptAttrCabinetsAll
        '
        ' network
        '
        rptNetworkLinksAll
        rptAttrNetworkAll
        rptPortDataAll
        '
        ' root reports
        '
        rptClientsAll
        rptAssetAll
        rptProductDataAll
        rptComponentsAll
        rptDGMasters


    End Enum

    '
    ' base reports that deal with software
    '
    Public Enum softwareReports
        rptApplicationsAll = baseReports.rptApplicationsAll
        rptApplicationsMoveStatus = baseReports.rptApplicationsMoveStatus
        rptApplicationsNetwork = baseReports.rptApplicationsNetwork
        rptApplicationsOperations = baseReports.rptApplicationsOperations
        rptOSAll = baseReports.rptOSAll
        rptVHAll = baseReports.rptVHAll
        rptAppConnectionsAll = baseReports.rptAppConnectionsAll
        rptAppSolutionsAll = baseReports.rptAppSolutionsAll
    End Enum

    '
    ' base reports that deal with location
    '
    Public Enum locationReports
        rptLocationsAll = baseReports.rptLocationsAll
        rptAttrLocationsAll = baseReports.rptAttrLocationsAll
        rptAttrGeoDataAll = baseReports.rptAttrGeoDataAll
        rptCabinetRowsAll = baseReports.rptCabinetRowsAll
    End Enum

    '
    ' base reports that deal with physical component(s)/attributes
    '
    Public Enum physicalcompReports
        rptAttrProcessorsAll = baseReports.rptAttrProcessorsAll
        rptAttrDrawAll = baseReports.rptAttrDrawAll
        rptDiskLogicalsAll = baseReports.rptDiskLogicalsAll
        rptDiskPhysicalsAll = baseReports.rptDiskPhysicalsAll
        rptDiskESAll = baseReports.rptDiskESAll
        rptAttrCabinetsAll = baseReports.rptAttrCabinetsAll
    End Enum

    Public Enum networkReports
        rptNetworkLinksAll = baseReports.rptNetworkLinksAll
        rptAttrNetworkAll = baseReports.rptAttrNetworkAll
        rptPortDataAll = baseReports.rptPortDataAll
    End Enum

    Public Enum rootReports
        rptClientsAll = baseReports.rptClientsAll
        rptAssetAll = baseReports.rptAssetAll
        rptProductDataAll = baseReports.rptProductDataAll
        rptComponentsAll = baseReports.rptComponentsAll
        rptDGMasters = baseReports.rptDGMasters
    End Enum


#End Region

#Region " IDisposable "

    Private disposedValue As Boolean = False

    Protected Overridable Sub Dispose(ByVal disposing As Boolean)
        If Not Me.disposedValue Then
            If disposing Then
                If Not (m_streams Is Nothing) Then
                    Dim stream As Stream
                    For Each stream In m_streams
                        stream.Close()
                    Next stream
                End If
            End If
        End If
        Me.disposedValue = True
    End Sub

    Public Sub Dispose() Implements IDisposable.Dispose
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub

#End Region

#Region " Methods "

    '
    ' for each of the baseReports setup the necessary viewer fields and set the object 
    ' table property (need when going from menu report)
    '
    Public Sub initReports _
        (ByVal intBaseReport As baseReports)

        Try

            ' clear the root datatable
            m_dt = Nothing
            _DataSource = "Unknown"
            _LocalViewer.Reset()
            _LocalViewer.LocalReport.DataSources.Clear()

            _baseReport = intBaseReport

            ' local report names must be preceded by root dll name
            Const strPath As String = "visRackAppConnectivity."


            ' what will the heading say
            Dim strRptName As String = [Enum].GetName(GetType(baseReports), intBaseReport)
            _DisplayName = strRptName

            ' what/where did we save the report definition xml
            Dim strRptXml As String = strRptName & ".rdlc"
            _Embedded = strPath & strRptXml

            Select Case intBaseReport
                '
                ' icmp reports
                '
                '
                ' snmp reports
                '

                '
                ' wmi reports
                '

                '
                ' location group
                '

                '
                ' network reports
                '
                '
                ' base table reports 
                '

                '
                'software reports
                '
                Case baseReports.rptApplicationsAll
                    _DataSource = "dc_Application"
                    _ObjectTable = DC_RackTables.tblAttrApplication
                    _SQLcall = visRackAppConnectivity.clsAttrApplications.readAll
                    Exit Select
                Case baseReports.rptAppConnectionsAll
                    _DataSource = "dc_AppConn"
                    _ObjectTable = DC_RackTables.tblAppConnection
                    _SQLcall = visRackAppConnectivity.clsAppConnections.readAll
                    Exit Select
                Case baseReports.rptAppSolutionsAll
                    _DataSource = "dc_AppSol"
                    _ObjectTable = DC_RackTables.tblAppSolution
                    _SQLcall = visRackAppConnectivity.clsAppSolutions.readAll
                    Exit Select

                    '
                    ' components/disk/storage
                    '

                Case Else
                    _DataSource = "Unknown"

            End Select


        Catch rpt As ReportViewerException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(rpt, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        Catch ex As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try


    End Sub

    '
    'http://support.microsoft.com/kb/323530
    '
    Public Class ClipboardMetafileHelper

        <DllImport("user32.dll", EntryPoint:="OpenClipboard", _
           SetLastError:=True, ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
        Public Shared Function OpenClipboard(ByVal hWnd As IntPtr) As Boolean
        End Function
        <DllImport("user32.dll", EntryPoint:="EmptyClipboard", _
           SetLastError:=True, ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
        Public Shared Function EmptyClipboard() As Boolean
        End Function
        <DllImport("user32.dll", EntryPoint:="SetClipboardData", _
           SetLastError:=True, ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
        Public Shared Function SetClipboardData(ByVal uFormat As Integer, ByVal hWnd As IntPtr) As IntPtr
        End Function
        <DllImport("user32.dll", EntryPoint:="CloseClipboard", _
           SetLastError:=True, ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
        Public Shared Function CloseClipboard() As Boolean
        End Function
        <DllImport("gdi32.dll", EntryPoint:="CopyEnhMetaFileA", _
           SetLastError:=True, ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
        Public Shared Function CopyEnhMetaFile(ByVal hemfSrc As IntPtr, ByVal hNULL As IntPtr) As IntPtr
        End Function
        <DllImport("gdi32.dll", EntryPoint:="DeleteEnhMetaFile", _
           SetLastError:=True, ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
        Public Shared Function DeleteEnhMetaFile(ByVal hemfSrc As IntPtr) As Boolean
        End Function
        '
        ' Metafile mf is set to a state that is not valid inside this function.
        '
        Public Shared Function PutEnhMetafileOnClipboard _
                (ByVal hWnd As IntPtr, _
                 ByVal mf As Metafile) _
                 As Boolean

            Dim bResult As New Boolean()
            bResult = False

            Try

                Dim hEMF As IntPtr = mf.GetHenhmetafile() ' invalidates mf
                If Not hEMF.Equals(New IntPtr(0)) Then
                    Dim hEMF2 As IntPtr = CopyEnhMetaFile(hEMF, New IntPtr(0))
                    If Not hEMF2.Equals(New IntPtr(0)) Then
                        If OpenClipboard(hWnd) Then
                            If EmptyClipboard() Then
                                Dim hRes As IntPtr
                                hRes = SetClipboardData(14, hEMF2)    ' 14 == CF_ENHMETAFILE
                                bResult = hRes.Equals(hEMF2)
                                CloseClipboard()
                            End If
                        End If
                    End If
                    DeleteEnhMetaFile(hEMF)
                End If

            Catch ex As Exception
                Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
                If (rethrow) Then
                    Throw
                End If
            End Try

            Return bResult

        End Function

    End Class

    '
    '
    '
    Public Sub createLocalReport()

        Try

            ' if no data get out
            If _DataTable Is Nothing Then
                MsgBox("ReportTable is missing")
            End If
            If _DataTable.Rows.Count < 1 Then
                MsgBox("ReportTable has no rows")
                Exit Sub
            End If
            If _DataSource Is Nothing _
                Or LCase(_DataSource) = "unknown" _
                Or LCase(_DataSource) = "uninitialized" Then
                MsgBox("ReportSource is in error")
                Exit Sub
            End If

            Dim strTableName As String = _DataTable.TableName.ToString

            If strTableName <> _DataSource Then
                _DataTable.TableName = _DataSource
            End If

            Dim myDataSource As New ReportDataSource(_DataSource, _DataTable)
            _LocalViewer.LocalReport.DataSources.Add(myDataSource)
            _LocalViewer.LocalReport.DisplayName = _DisplayName
            _LocalViewer.LocalReport.ReportEmbeddedResource = _Embedded

            _LocalViewer.RefreshReport()


        Catch vwr As ReportViewerException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(vwr, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        Catch ex As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

    End Sub

    '
    ' pass in the datatable/selector and return either a sql string or reportname
    ' this is where we map table names to the reports that we want
    '
    ' Dim intReport As baseReports = [Enum].Parse(GetType(baseReports), getReportDataTable(intTable, "report"))
    ' Dim intTable As DC_RackTables = [Enum].Parse(GetType(DC_RackTables), CurrentTable.Text)
    ' Dim m_sql As String = getReportDataTable(_objecttable, "sql")
    ' Dim cmd As DbCommand = m_db.GetStoredProcCommand(m_sql)
    ' m_ds = m_db.ExecuteDataSet(cmd)
    ' m_dt = m_ds.Tables.Item(0)
    '




#End Region

#Region " Render Report as Metafile "

    '
    '
    '
    Public Function RenderReportMetafileAsMetafile() As Metafile


        Try

            Dim PageSettings As ReportPageSettings
            PageSettings = _LocalViewer.LocalReport.GetDefaultPageSettings

            'Debug.WriteLine(PageSettings.Margins.Top)
            'Debug.WriteLine(PageSettings.Margins.Bottom)
            'Debug.WriteLine(PageSettings.Margins.Left)
            'Debug.WriteLine(PageSettings.Margins.Right)
            'Debug.WriteLine(PageSettings.PaperSize.Kind)
            'Debug.WriteLine(PageSettings.PaperSize.RawKind)
            'Debug.WriteLine(PageSettings.PaperSize.PaperName)

            ' the height and width properties appear to be coming through 
            ' from the report switched
            Dim intPageWidth As Single = PageSettings.PaperSize.Height / 100
            Dim intPageHeight As Single = PageSettings.PaperSize.Width / 100

            Dim strHeight As String = String.Format("{0:N}", intPageHeight)
            Dim strWidth As String = String.Format("{0:N}", intPageWidth)


            Dim format As String = "Image" ' input
            Dim deviceInfo As String = _
                    "<DeviceInfo>" + _
                    "  <OutputFormat>EMF</OutputFormat>" + _
                    "  <PageWidth>" & strWidth & "in</PageWidth>" + _
                    "  <PageHeight>" & strHeight & "in</PageHeight>" + _
                    "  <MarginTop>0.25in</MarginTop>" + _
                    "  <MarginLeft>0.25in</MarginLeft>" + _
                    "  <MarginRight>0.25in</MarginRight>" + _
                    "  <MarginBottom>0.25in</MarginBottom>" + _
                    "</DeviceInfo>"

            Dim mimeType As String = Nothing ' output
            Dim encoding As String = Nothing ' output
            Dim fileNameExtension As String = Nothing ' output
            Dim streams As String() = Nothing ' output
            Dim warnings As Warning() = Nothing ' output

            m_streams = Nothing
            m_streams = New List(Of Stream)()
            _LocalViewer.LocalReport.Render("Image", deviceInfo, _
                  AddressOf CreateStream, warnings)

            Dim stream As Stream
            For Each stream In m_streams
                stream.Position = 0
            Next

        Catch rpt As Microsoft.Reporting.WinForms.LocalProcessingException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(rpt, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        Catch ex As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

        Dim emfImage As New Metafile(m_streams(0))

        RenderReportMetafileAsMetafile = emfImage

    End Function

    '
    '
    '
    Public Function RenderReportMetafileAsByte() As Byte()

        Dim returnValue As Byte() = Nothing

        Try

            Dim PageSettings As ReportPageSettings
            PageSettings = _LocalViewer.LocalReport.GetDefaultPageSettings


            ' the height and width properties appear to be coming through 
            ' from the report switched
            Dim intPageWidth As Single = PageSettings.PaperSize.Height / 100
            Dim intPageHeight As Single = PageSettings.PaperSize.Width / 100

            Dim strHeight As String = String.Format("{0:N}", intPageHeight)
            Dim strWidth As String = String.Format("{0:N}", intPageWidth)


            Dim format As String = "Image" ' input
            Dim deviceInfo As String = _
                    "<DeviceInfo>" + _
                    "  <OutputFormat>EMF</OutputFormat>" + _
                    "  <PageWidth>" & strWidth & "in</PageWidth>" + _
                    "  <PageHeight>" & strHeight & "in</PageHeight>" + _
                    "  <MarginTop>0.25in</MarginTop>" + _
                    "  <MarginLeft>0.25in</MarginLeft>" + _
                    "  <MarginRight>0.25in</MarginRight>" + _
                    "  <MarginBottom>0.25in</MarginBottom>" + _
                    "</DeviceInfo>"

            Dim mimeType As String = Nothing ' output
            Dim encoding As String = Nothing ' output
            Dim fileNameExtension As String = Nothing ' output
            Dim streams As String() = Nothing ' output
            Dim warnings As Warning() = Nothing ' output

            returnValue = _LocalViewer.LocalReport.Render(format, deviceInfo, mimeType, encoding, fileNameExtension, streams, warnings)


        Catch rpt As Microsoft.Reporting.WinForms.LocalProcessingException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(rpt, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        Catch ex As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

        RenderReportMetafileAsByte = returnValue

    End Function

    '
    '
    '
    Public Sub copyReportEmfToClipboard()

        Try

            ClipboardMetafileHelper.PutEnhMetafileOnClipboard(_TargetWindow, RenderReportMetafileAsMetafile())

        Catch ex As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

    End Sub

    '
    '
    '
    Private Sub outputPrintEMF()

        RenderReportMetafileAsMetafile()

        m_currentPageIndex = 0

        ImageWriterPrint()

    End Sub

    '
    '
    '
    Private Sub ImageWriterPrint()

        Const printerName As String = "Microsoft Office Document Image Writer"

        If m_streams Is Nothing Or m_streams.Count = 0 Then
            Return
        End If

        Dim printDoc As New PrintDocument()
        printDoc.PrinterSettings.PrinterName = printerName
        If Not printDoc.PrinterSettings.IsValid Then
            Dim msg As String = String.Format( _
                 "Can't find printer ""{0}"".", printerName)
            MsgBox(msg)
            Return
        End If

        AddHandler printDoc.PrintPage, AddressOf PrintPage
        printDoc.Print()

    End Sub

    '
    '
    '
    Private Function CreateStream _
                (ByVal name As String, _
                ByVal fileNameExtension As String, _
                ByVal encoding As Encoding, _
                ByVal mimeType As String, _
                ByVal willSeek As Boolean) As Stream

        Dim stream As Stream = New FileStream(name + "." + fileNameExtension, FileMode.Create)
        m_streams.Add(stream)

        Return stream

    End Function

    '
    '
    '
    Private Sub PrintPage(ByVal sender As Object, ByVal ev As PrintPageEventArgs)

        Dim pageImage As New Metafile(m_streams(m_currentPageIndex))
        ev.Graphics.DrawImage(pageImage, ev.PageBounds)

        m_currentPageIndex += 1
        ev.HasMorePages = (m_currentPageIndex < m_streams.Count)

    End Sub

#End Region

#Region " Render Report As Text "

    '
    ' using the input datatable, get the columnames and
    ' return a csv string
    '
    Private Function getColumnNames() As String

        Dim strColumns As String = ""
        Dim strColumnName As String = ""
        Dim tempDataColumn As DataColumn
        Dim colNames As Collection = New Collection


        If Not (_DataTable Is Nothing) Then
            For Each tempDataColumn In _DataTable.Columns
                strColumnName = tempDataColumn.ColumnName
                colNames.Add(strColumnName)
            Next tempDataColumn
        End If
        strColumns = BuildCsvString(colNames)
        getColumnNames = strColumns

    End Function

    '
    ' take an input collection and make a csv string
    '
    Private Function BuildCsvString _
        (ByVal colA As Collection) _
        As String

        Dim intY As Integer
        Dim strCsv As String = ""
        Try

            If (colA Is Nothing) _
                Or (colA.Count = 0) Then
                Exit Try
            Else
                With colA
                    For intY = 1 To colA.Count
                        strCsv = strCsv & CStr(colA.Item(intY))
                        If intY <> colA.Count Then
                            strCsv = strCsv & ","
                        End If ' test for last position
                    Next intY
                End With
            End If

        Catch ex As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
            strCsv = ""
        End Try

        BuildCsvString = strCsv


    End Function

    '
    ' take the existing datatable and make it a csv text string
    '
    Public Function RenderReportText() As String

        Dim strReturn As String = ""
        Dim tempDataRow As DataRow = Nothing
        Dim tempDataColumn As DataColumn = Nothing
        Dim colTempRow As Collection = New Collection
        Dim intColCt As Integer = 0
        Dim intRowCt As Integer = 0
        Dim intX As Integer = 0
        Dim intY As Integer = 0

        Try
            If Not (_DataTable Is Nothing) Then
                strReturn = getColumnNames() & vbCrLf
                intColCt = _DataTable.Columns.Count - 1
                intRowCt = _DataTable.Rows.Count - 1
                For intY = 0 To intRowCt
                    tempDataRow = _DataTable.Rows(intY)
                    colTempRow = Nothing
                    colTempRow = New Collection
                    For intX = 0 To intColCt
                        colTempRow.Add(tempDataRow.Item(intX).ToString)
                    Next intX
                    strReturn = strReturn & BuildCsvString(colTempRow)
                    If intY <> intRowCt Then
                        strReturn = strReturn & vbCrLf
                    End If
                Next intY
            End If

        Catch ex As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

        RenderReportText = strReturn

    End Function

#End Region

#Region " Render standard report "
    '
    ' this is just a recasting of the standard render method
    '
    Public Function RenderReportStandard(ByVal strFormat As String) As Byte()

        Dim bytes As Byte() = Nothing

        Try

            If strFormat <> "PDF" _
                Or strFormat <> "Excel" Then
                Exit Try
            End If

            Dim warnings As Warning() = Nothing
            Dim streamids As String() = Nothing
            Dim deviceInfo As String = Nothing
            Dim mimeType As String = Nothing
            Dim encoding As String = Nothing
            Dim extension As String = Nothing

            bytes = _LocalViewer.LocalReport.Render(strFormat, _
                        deviceInfo, _
                        mimeType, _
                        encoding, _
                        extension, _
                        streamids, _
                        warnings)

        Catch rpt As Microsoft.Reporting.WinForms.LocalProcessingException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(rpt, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        Catch ex As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

        RenderReportStandard = bytes

    End Function

#End Region

#Region " Constructor "


    Public Sub New()

        _LocalViewer = Nothing
        _DataSource = ""

        _baseReport = baseReports.rptUnknown
        _ObjectTable = DC_RackTables.tblUnknown


        m_db = DatabaseFactory.CreateDatabase()

        ' make sure the root stuff is there
        If m_ds Is Nothing Then
            m_ds = New DataSet
        Else
            m_ds = Nothing
            m_ds = New DataSet
        End If
        m_ds.SchemaSerializationMode = SchemaSerializationMode.IncludeSchema

        If m_dt Is Nothing Then
            m_dt = New DataTable
        Else
            m_dt = Nothing
            m_dt = New DataTable
        End If

    End Sub

    Public Sub New _
        (ByRef locViewer As ReportViewer, _
         ByVal intBaseReport As baseReports, _
         ByVal dtReport As DataTable)

        Try

            m_db = DatabaseFactory.CreateDatabase()

            ' make sure the root stuff is there
            If m_ds Is Nothing Then
                m_ds = New DataSet
            Else
                m_ds = Nothing
                m_ds = New DataSet
            End If

            m_ds.SchemaSerializationMode = SchemaSerializationMode.IncludeSchema

            ' map the report control over here
            _LocalViewer = locViewer

            ' this sets up the datasource name for the report
            ' and saves an ObjectName(table) in case we are not passed
            ' a datatable
            initReports(intBaseReport)


            ' map the datatable
            If dtReport IsNot Nothing Then
                _DataTable = dtReport
            Else
                Dim cmd As DbCommand = m_db.GetStoredProcCommand(_SQLcall)
                m_ds = m_db.ExecuteDataSet(cmd)
                _DataTable = m_ds.Tables.Item(0)
            End If

            createLocalReport()



        Catch rpt As ReportViewerException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(rpt, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        Catch ex As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

    End Sub

#End Region



End Class
